import 'package:hive/hive.dart';

import '../index.dart';

class ShareService {
  static const String _boxName = 'shares';

  static Future<void> initialize() async {
    // 注册适配器（必须在打开box之前）
    if (!Hive.isAdapterRegistered(1)) {
      Hive.registerAdapter(ShareEntityAdapter());
    }

    // 打开shares数据盒子
    await Hive.openBox<ShareEntity>(_boxName);

    // 初始化默认分享数据
    await _initializeDefaultShares();
  }

  static Future<void> _initializeDefaultShares() async {
    final box = Hive.box<ShareEntity>(_boxName);

    // 如果数据库为空，添加默认用户
    if (box.isEmpty) {
      for (final share in sampleShares) {
        await box.put(share.id, share);
      }
    }
  }

  // 根据Id获取share
  static Future<List<ShareEntity>> getSharesById(String id) async {
    final box = Hive.box<ShareEntity>(_boxName);
    return box.values.where((share) => share.id == id).toList();
  }

  // 根据用户id获取share
  static Future<List<ShareEntity>> getSharesByUserId(String userId) async {
    final box = Hive.box<ShareEntity>(_boxName);
    final user = await UserService.getUserById(userId);

    if (user == null) {
      return [];
    }

    final shares = box.values
        .where((share) => user.share.contains(share.id))
        .toList();

    return shares;
  }

  // 获取所有分享
  static Future<List<ShareEntity>> getAllShares() async {
    final box = Hive.box<ShareEntity>(_boxName);
    return box.values.toList();
  }

  // 获取所有分享（过滤被举报的内容）
  static Future<List<ShareEntity>> getAllSharesFiltered() async {
    final box = Hive.box<ShareEntity>(_boxName);
    final currentUser = UserService.getCurrentUser();

    if (currentUser == null) {
      return box.values.toList();
    }

    // 过滤被举报的帖子和被举报用户的帖子
    final allShares = box.values.toList();
    final filteredShares = <ShareEntity>[];

    for (final share in allShares) {
      // 检查是否举报了这个帖子
      if (currentUser.reportedPosts.contains(share.id)) {
        continue;
      }

      // 检查是否举报了这个帖子的作者
      final author = getShareAuthor(share);
      if (author != null && currentUser.reportedUsers.contains(author.id)) {
        continue;
      }

      filteredShares.add(share);
    }

    return filteredShares;
  }

  // 根据分享ID列表获取分享
  static Future<List<ShareEntity>> getSharesByIds(List<String> shareIds) async {
    final box = Hive.box<ShareEntity>(_boxName);
    return box.values.where((share) => shareIds.contains(share.id)).toList();
  }

  // 更新分享
  static Future<void> updateShare(ShareEntity share) async {
    final box = Hive.box<ShareEntity>(_boxName);
    await box.put(share.id, share);
  }

  // 创建新分享
  static Future<bool> createShare(ShareEntity share) async {
    try {
      final box = Hive.box<ShareEntity>(_boxName);
      await box.put(share.id, share);
      return true;
    } catch (e) {
      print('创建分享失败: $e');
      return false;
    }
  }

  /// 获取分享的作者信息
  /// 通过遍历所有用户，查找哪个用户的share字段包含该分享ID
  static UserEntity? getShareAuthor(ShareEntity share) {
    final allUsers = UserService.getAllUsers();

    for (final user in allUsers) {
      if (user.share.contains(share.id)) {
        return user;
      }
    }

    // 如果没找到作者，返回默认用户（确保列表不为空）
    final defaultUsers = UserEntity.defaultUsers;
    if (defaultUsers.isNotEmpty) {
      return defaultUsers.first;
    }

    // 最后的备选方案：创建一个临时用户
    return UserEntity(
      id: 'temp',
      username: 'Unknown',
      password: '',
      avatar: MyImages.mark,
      share: [],
      isVip: false,
      like: [],
    );
  }
}
